
package com.sq.partner.manager.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sq.partner.manager.mybatis.model.EinvoiceDto;
import com.sq.partner.manager.service.NocarInvoiceInfoService;
import com.sq.partner.manager.util.JsonUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.CoreDept;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TGatewayInvoice;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.service.IGatewayLifePolicyListService;
import com.sq.partner.manager.service.IPushInfoManagerService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author myl
 */
@Controller
@RequestMapping("/pushInfoManagerController")
public class PushInfoManagerController {
	private static Logger logger = LogUtil.getLog(PushInfoManagerController.class);
	@Resource
	IPushInfoManagerService pushInfoManagerService;
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	
	@Resource
	private IGatewayLifePolicyListService lifePolicyListService;

	@Resource
	NocarInvoiceInfoService nocarInvoiceInfoService;

	/**
	 * 跳转推送发票信息页面
	 */
	@RequestMapping(value = "/list")
	public String list(HttpSession session,ModelMap model) throws Exception { 
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		model.put("privilegeBranch", user.getUserComcode());
		return "pushInfoManage/pushInvoiceConfig";
	}
	
	/**
	 * 跳转推送保单数据页面
	 */
	@RequestMapping(value = "/pushPolicylist")
	public String pushPolicylist(HttpSession session,ModelMap model) throws Exception { 
		return "pushInfoManage/pushPolicyConfig";
	}

	/**
	 * 跳转推送保单数据页面
	 */
	@RequestMapping(value = "/queryEinvoice")
	public String queryEinvoice(HttpSession session,ModelMap model) throws Exception {
		return "pushInfoManage/queryEinvoiceConfig";
	}

	/**
	 * 跳转推送保单数据页面
	 */
	@RequestMapping(value = "/queryNocarInvoice")
	public String queryNocarInvoice(HttpSession session,ModelMap model) throws Exception {
		return "pushInfoManage/queryNocarInvoiceConfig";
	}
	/**
	 * 查询当前用户的权限机构
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryPrivilegeBranch",method = RequestMethod.POST)
	@ResponseBody
    public Result queryPrivilegeBranch(HttpSession session) throws Exception {
		GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		logger.info("当前登录用户的userCode为"+user.getUserCode()+",DepartmentStr:"+user.getDepartmentStr());
		
		List<String> userDeptList = pushInfoManagerService.queryUserDept(user.getUserid()+"");
		if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
			return Result.data(pushInfoManagerService.queryPrivilegeBranch(userDeptList));
		}
		
		return Result.fail();
    }
	/**
	 * 查询传入机构及其子机构
	 * @param size
	 * @param pageIndex
	 * @param deptCode
	 * @param deptCNname
	 * @param parentCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/queryDeptByDeptAndParentDeptCode",method = RequestMethod.POST)
	@ResponseBody
	public Page<CoreDept> queryDeptByDeptAndParentDeptCode(Integer size,Integer pageIndex,
				String deptCode,String deptCname,String parentDeptCode) throws Exception{
		if(StrUtil.isEmpty(parentDeptCode)){
			throw new AppException("机构不能为空");
		}
		
		Page<CoreDept> page=new Page<CoreDept>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		CoreDept dept=new CoreDept();
		dept.setDeptCode(deptCode);
		dept.setDeptCname(deptCname);
		page.setType(dept);

		return lifePolicyListService.queryDeptPageByDeptAndParentDeptCode(page, parentDeptCode);
	}
	
	
	/**
	 * 查询合作伙伴
	 * @param fkAppid
	 * @return List<GatewayChannelInfo>
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryChannelInfo",method = RequestMethod.POST)
	public @ResponseBody Page<GatewayChannelInfo> queryChannelInfo(Integer size,Integer pageIndex,
									String parentDeptCode,String channelName,String channelCode) throws Exception{
		if(StrUtil.isEmpty(parentDeptCode)){
			throw new AppException("机构不能为空");
		}
		
		Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
		page.setCurrent(pageIndex);
		page.setSize(size);
		
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setDeptCode(parentDeptCode);
		channelInfo.setChannelCode(channelCode);
		channelInfo.setChannelName(channelName);
		page.setType(channelInfo);
		return pushInfoManagerService.queryChannelInfoPage(page);
	}
	
	@RequestMapping(value = "/queryInviocePageByCriteria")
    @ResponseBody
    public Page queryInviocePageByCriteria(HttpSession session, Integer pageIndex,
    		String privilegeBranch, String partnerNo, String dptCde, String polNo, String status) throws Exception {
		Page page = new Page();
		Map<String,Object> map = new HashMap<String, Object>();
		if(pageIndex != -1){
			page.setCurrent(pageIndex);
			map = SqlUtil.buildPageMap(page);
		}		
		//机构验证
		if(StrUtil.isEmpty(privilegeBranch)){
			throw new AppException("系统异常：机构不能为空");
		}else{
			if(!(channelInfoConfigService.checkIsHasPrivilege(session, privilegeBranch))){
				throw new AppException("用户权限不足");
			}	
		}
		if("00".equals(privilegeBranch)){
            map.put("isHq", 'Y');
        } else {
            map.put("isHq", 'N');
        }
		map.put("privilegeBranch",privilegeBranch);
		map.put("dptCode", dptCde);
		map.put("channelCode", partnerNo);
		map.put("polNo", polNo);
		map.put("status", status);
		page.setType(map); 
		
		if("error".equals(page.getResult()) || "noChannelInfo".equals(page.getResult())){
            return page;
        }
        return pushInfoManagerService.queryInviocePageByCriteria(page);
    }
	
	/***
	 * 发票信息修改
	 */
	@RequestMapping(value = "/saveInvioce", method = RequestMethod.POST)
	@ResponseBody
	public Result saveInvioce(HttpSession session,TGatewayInvoice tGatewayInvoice) throws Exception {
		//GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		if(tGatewayInvoice==null){
			return Result.error("参数不可以为空");
		}
		try {
			pushInfoManagerService.editInvioceGroup(tGatewayInvoice);
			return Result.success("修改成功");
		} catch (Exception e) {
			logger.info(e);
			return Result.error("系统错误");
		}
	}
	
	/***
	 * 发票推送之前处理
	 */
	@RequestMapping(value = "/beforePushInvioce", method = RequestMethod.POST)
	@ResponseBody
	public Result beforePushInvioce(HttpSession session,HttpServletRequest request,HttpServletResponse response, String channelCodeStr, String invioceIDStr) throws Exception {
		String[]  channelCodes = dealInvioceID(channelCodeStr);
		String[]  invioceIDs = dealInvioceID(invioceIDStr);
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("channelCodes", channelCodes);
			map.put("invioceIDs", invioceIDs);
			List<Map<String, Object>> beforePushInvioceList = pushInfoManagerService.beforePushInvioce(map);
			String flag = "" ; 
			for (int i = 0; i < beforePushInvioceList.size(); i++) {
				for (Object key : beforePushInvioceList.get(i).keySet()) {
					if("IS_SEND_INVOICE".equals(key)){
						if(!"1".equals(beforePushInvioceList.get(i).get(key))){
							flag += "   //"+beforePushInvioceList.get(i).get("POLNO");
						}
						
					}
				}
			}
			return Result.success(flag);
		} catch (Exception e) {
			logger.info(e);
			return Result.error("系统错误");
		}
	}
	
	/***
	 * 发票推送
	 */
	@RequestMapping(value = "/pushInvioce", method = RequestMethod.POST)
	@ResponseBody
	public Result pushInvioce(HttpSession session,HttpServletRequest request,HttpServletResponse response, String invioceIDStr) throws Exception {
		String[]  invioceIDs = dealInvioceID(invioceIDStr);
		try {
			String resultInfo = "发票推送结果:" + "   ";
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("invioceIDs", invioceIDs);
			List<Map<Object, Object>> resultList = pushInfoManagerService.queryInvioceByID(map);
			for (int i = 0; i < resultList.size(); i++) {
				for (Object key : resultList.get(i).keySet()) {
					resultInfo +="        //保单号"+(String)key +":"+ resultList.get(i).get(key) ;		
				}
			}
			return Result.success(resultInfo);
		} catch (Exception e) {
			logger.info(e);
			return Result.error("系统错误");
		}
	}
	/*产品编码处理*/
	private String[] dealInvioceID(String invioceIDs) {
		if(StrUtil.isEmpty(invioceIDs)){
			return null;
		}
		String[] strs=invioceIDs.split(",");
		return strs;
	}
	
	/**
	 * 合作伙伴是否配送发票查询
	 */
	@RequestMapping(value = "/queryIsPushInvioce", method = RequestMethod.POST)
	@ResponseBody
	public Result queryIsPushInvioce(HttpSession session,HttpServletRequest request,HttpServletResponse response, String partnerNo) throws Exception {
		try {
			Map<String, String> isPushInvioceMap = pushInfoManagerService.queryIsPushInvioceBypartnerNo(partnerNo);
			String isSendInvioce = "";
			for (Object key : isPushInvioceMap.keySet()) {
				if("IS_SEND_INVOICE".equals(key)){			
					isSendInvioce = isPushInvioceMap.get(key);
				}
			}
			return Result.success(isSendInvioce);
		} catch (Exception e) {
			logger.info(e);
			return Result.error("系统错误");
		}
	}
	/***
	 * 保单推送
	 */
	@RequestMapping(value = "/pushPolicyInfo", method = RequestMethod.POST)
	@ResponseBody
	public Result pushPolicyInfo(HttpSession session,HttpServletRequest request,HttpServletResponse response, String polNo) throws Exception {
		try {
			String resultInfo = pushInfoManagerService.pushPolicyInfo(polNo);
			return Result.success(resultInfo);
		} catch (Exception e) {
			logger.info(e);
			return Result.error("系统错误");
		}
	}

	/**
	 * 根据保单号或者list查询发票
	 */
	@RequestMapping(value = "/queryEinvoiceByPolList",method = RequestMethod.POST)
	@ResponseBody
	public Result queryEinvoiceBypolno(@RequestParam("polNoList[]") String[] polNoList) {
		try{
			List<EinvoiceDto> list = pushInfoManagerService.queryEinvoiceByPolList(polNoList);
			return Result.success(list);
		}catch (Exception e){
			logger.info(e);
			return Result.error("系统错误，错误原因：" + e);
		}

	}

	/**
	 * 重开发票
	 */
	@RequestMapping(value = "/rePushByPol", method = RequestMethod.POST)
	@ResponseBody
	public Result rePushByPol(@RequestParam("polNo") String polNo){
		try{
			pushInfoManagerService.rePushByPol(polNo);
			return Result.success("重开成功");
		}catch (Exception e){
			logger.info(e);
			return Result.error("系统错误");
		}
	}

	/**
	 * 批量重开发票
	 */

	@RequestMapping(value = "/rePushByPolList",method = RequestMethod.POST)
	@ResponseBody
	public Result rePushByPolList (@RequestParam("polNoList") String polNoList){
		try{
			pushInfoManagerService.rePushByPolList(polNoList);
			return Result.success("重开成功");
		}catch (Exception e){
			logger.info(e);
			return Result.error("系统错误");
		}
	}


	/**
	 * 保单号查询发票模板下载
	 */
	@RequestMapping(value = "/downloadPolnoTemplet",method = RequestMethod.GET)
	public void downloadPolnoTemplet(HttpServletResponse response,HttpServletRequest request ,String templateType) throws IOException {
		System.out.println("模板下载开始...");
		String classPath=this.getClass().getResource("").getPath();
		String path="";
		if(StrUtil.isEmpty(templateType)){
			logger.info("模板类型传入参数为空结束程序");
			return;
		}else if("PolNoList".equals(templateType)){
			path = (classPath.substring(0,classPath.indexOf("/WEB-INF/")+8)+ "/file/PolNoList_templet.xls").replace("/WEB-INF", "");
		}else{
			logger.info("模板类型传入参数为非法参数结束程序");
			return ;
		}
		// 以流的形式下载文件
		InputStream inputStream=null;
		OutputStream outputStream =null;
		File file = new File(path);
		try {
			// 取得文件名。
			String filename = file.getName();
			inputStream = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[inputStream.available()];
			inputStream.read(buffer);
			//清空response
			response.reset();
			//设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			response.addHeader("Content-Length", "" + file.length());
			outputStream = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			outputStream.write(buffer);
			outputStream.flush();
		} catch (Exception e) {
			logger.info(e);
		} finally {
			if(null!=inputStream){
				inputStream.close();
			}
			if(null!=outputStream){
				outputStream.close();
			}
		}
	}

	/**
	 * excel上传
	 */
	@RequestMapping(value = "/xlsPolNoListFileUpload")
	public void addUserAgentInfo(@RequestParam MultipartFile[] fileToUpload, HttpServletResponse response, HttpSession session) throws Exception {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		List<InputStream> inputStreams = null;
		Page<String>  page = new Page<String>();
		List<String> polList = new ArrayList<String>();
		// 上传文件的原名(即上传前的文件名字)
		try {
			out = response.getWriter();
			if (fileToUpload.length < 1) {
				page.setResult("error");
				page.setMessage("请添加上传文件!");
			}else{
				GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
				inputStreams=pushInfoManagerService.getFileInputStream(fileToUpload);
				polList = pushInfoManagerService.insertPolNoList(inputStreams.get(0),user,session);
				logger.info("清单读写成功");
				page.setResult("success");
				page.setMessage((String)session.getAttribute("result"));
				page.setData(polList);
			}
		} catch (Exception e) {
			logger.info("---------Excel导入失败",e);
			page.setResult("error");
			page.setMessage(e.getMessage());
		} finally {
			if(null!=inputStreams){
				for (InputStream input:inputStreams){
					try{
						input.close();
					}catch(Exception e){
						logger.warn("关闭流失败！", e);
					}
				}
			}
			out.write(JsonUtils.toJson(page));
			try {
				out.close();
			} catch (Exception e) {
				logger.warn("关闭流失败！", e);
			}
		}
	}

	@RequestMapping(value = "/queryNocarInviocePageByCriteria")
	@ResponseBody
	public Page queryNocarInviocePageByCriteria(HttpSession session, Integer pageIndex,
										   String privilegeBranch, String partnerNo, String dptCde, String polNo, String applicationNo) throws Exception {
		Page page = new Page();
		Map<String,Object> map = new HashMap<String, Object>();
		if(pageIndex != -1){
			page.setCurrent(pageIndex);
			map = SqlUtil.buildPageMap(page);
		}
		//机构验证
		if(StrUtil.isEmpty(privilegeBranch)){
			throw new AppException("系统异常：机构不能为空");
		}else{
			if(!(channelInfoConfigService.checkIsHasPrivilege(session, privilegeBranch))){
				throw new AppException("用户权限不足");
			}
		}
		if("00".equals(privilegeBranch)){
			map.put("isHq", 'Y');
		} else {
			map.put("isHq", 'N');
		}
		map.put("privilegeBranch",privilegeBranch);
		map.put("dptCode", dptCde);
		map.put("channelCode", partnerNo);
		map.put("polNo", polNo);
		map.put("applicationNo", applicationNo);
		page.setType(map);

		if("error".equals(page.getResult()) || "noChannelInfo".equals(page.getResult())){
			return page;
		}
		return nocarInvoiceInfoService.queryInviocePageByCriteria(page);
	}

}

